package com.k3cloud.user.user;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class K3CloudHttpService {


    private boolean autoCookie;
    private String kdserviceSessionid;
    private String cookieStr;

    public String plmEntityOid;




    public boolean isAutoCookie() {
        return autoCookie;
    }
    public void setAutoCookie(boolean autoCookie) {
        this.autoCookie = autoCookie;
    }

    public String getCookieStr() {
        return cookieStr;
    }

    public void setCookieStr(String cookieStr) {
        this.cookieStr = cookieStr;
    }

    public String getKdserviceSessionid() {
        return kdserviceSessionid;
    }

    public void setKdserviceSessionid(String kdserviceSessionid) {
        this.kdserviceSessionid = kdserviceSessionid;
    }



    public static BigInteger generateUniqueId() {
        long timestamp = Instant.now().toEpochMilli();
        long sequence = System.nanoTime() % 1000000;

        String idStr = timestamp + "" + 1 + "" + sequence;
        return new BigInteger(idStr);
    }





    //递归获取BOM
    public void getRecursionBom(Set<PartBomTree> list, List<PartBomTree> bomList){
        for( PartBomTree partBomTree: list) {
            if(partBomTree.getChildren()!=null && partBomTree.getChildren().size()>0){
                bomList.add(partBomTree);
                getRecursionBom(partBomTree.getChildren(),bomList);
            }
        }
    }



    public static String changeCharset(String str, String newCharset) {
        try {
            if (str != null) {
                //用默认字符编码解码字符串。
                byte[] bs = str.getBytes();
                //用新的字符编码生成字符串
                return new String(bs, newCharset);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    private static void setParameterToTree(List<Map<String, Object>> list,String parentId,Map<String,Object> entity){
        for(int i=0;i<list.size();i++){
            Map<String, Object> map=list.get(i);
            if(parentId.equals(map.get("parent_id"))){
                entity.put((String) map.get("node"),map);
                setParameterToTree(list,(String) map.get("id"),map);
            }
        }
    }


    public List<Map<String,Object>> jsonObjectToList(String json,String analysis){
        JSONObject obj=JSONObject.parseObject(json);
        List<Map<String,Object>> list=new ArrayList<>();
        jsonObjectChlider(list,obj,null,null,analysis);
        return list;
    }
    public void jsonObjectChlider(List<Map<String,Object>> list,Object entity,String entityUuid,String entityKey,String analysis){
        if(entity instanceof JSONObject){
            JSONObject f=(JSONObject) entity;
            for(Map.Entry<String,Object> e: f.getInnerMap().entrySet()){
                if(e.getValue() instanceof JSONObject){
                    Map<String,Object> map=new HashMap<>();
                    String uuid=UUID.randomUUID().toString();
                    map.put("id",uuid);
                    map.put("node",e.getKey());
                    map.put("node_key",uuid.replaceAll("-",""));
                    if(entityUuid==null){
                        map.put("parent_id","0");
                    }
                    else{
                        map.put("parent_id",entityUuid);
                    }
                    map.put("data_type",0);
                    map.put("valuation_type",0);
                    list.add(map);

                    jsonObjectChlider(list,e.getValue(),uuid,e.getKey(),analysis);
                }
                else if(e.getValue() instanceof JSONArray){
                    jsonObjectChlider(list,e.getValue(),entityUuid,e.getKey(),analysis);
                }
                else{
                    Map<String,Object> map=new HashMap<>();
                    String uuid=UUID.randomUUID().toString();
                    map.put("id",uuid);
                    map.put("node",e.getKey());
                    map.put("node_key",uuid.replaceAll("-",""));
                    if(entityUuid==null){
                        map.put("parent_id","0");
                    }
                    else{
                        map.put("parent_id",entityUuid);
                    }
                    dataType(map,e.getValue().getClass().getName(),e.getValue());
                    list.add(map);
                }
            }
        }
        else if(entity instanceof JSONArray){
            JSONArray arr=(JSONArray) entity;

            if(arr.size()==0){
                Map<String,Object> map=new HashMap<>();
                String uuid=UUID.randomUUID().toString();
                map.put("id",uuid);
                map.put("node",entityKey);
                map.put("node_key",uuid.replaceAll("-",""));
                if(entityUuid==null){
                    map.put("parent_id","0");
                }
                else{
                    map.put("parent_id",entityUuid);
                }
                map.put("data_type",5);
                map.put("valuation_type",0);
                list.add(map);
            }
            else{
                if("1".equals(analysis)){
                    Map<String,Object> map=new HashMap<>();
                    String uuid=UUID.randomUUID().toString();
                    map.put("id",uuid);
                    map.put("node",entityKey);
                    map.put("node_key",uuid.replaceAll("-",""));
                    if(entityUuid==null){
                        map.put("parent_id","0");
                    }
                    else{
                        map.put("parent_id",entityUuid);
                    }
                    map.put("data_type",-2);
                    map.put("valuation_type",0);
                    list.add(map);
                    for(int i=0;i<arr.size();i++){
                        map=new HashMap<>();
                        String auuid=UUID.randomUUID().toString();
                        map.put("id",auuid);
                        map.put("node",i);
                        map.put("node_key",auuid.replaceAll("-",""));
                        if(entityUuid==null){
                            map.put("parent_id","0");
                        }
                        else{
                            map.put("parent_id",uuid);
                        }
                        map.put("data_type",0);
                        map.put("valuation_type",0);
                        list.add(map);
                        jsonObjectChlider(list,arr.get(i),auuid,uuid,analysis);
                    }
                }
                else{
                    if(arr.get(0) instanceof JSONObject){
                        Map<String,Object> map=new HashMap<>();
                        String uuid=UUID.randomUUID().toString();
                        map.put("id",uuid);
                        map.put("node",entityKey);
                        map.put("node_key",uuid.replaceAll("-",""));
                        if(entityUuid==null){
                            map.put("parent_id","0");
                        }
                        else{
                            map.put("parent_id",entityUuid);
                        }
                        map.put("data_type",-1);
                        map.put("valuation_type",0);
                        list.add(map);
                        jsonObjectChlider(list,arr.get(0),uuid,entityKey,analysis);
                    }
                    else if(arr.get(0) instanceof JSONArray){
                        //jsonObjectChlider(list,arr.get(i),entityUuid,entityKey);
                    }
                    else{
                        Map<String,Object> map=new HashMap<>();
                        String uuid=UUID.randomUUID().toString();
                        map.put("id",uuid);
                        map.put("node",entityKey);
                        map.put("node_key",uuid.replaceAll("-",""));
                        if(entityUuid==null){
                            map.put("parent_id","0");
                        }
                        else{
                            map.put("parent_id",entityUuid);
                        }
                        map.put("data_type",5);
                        map.put("valuation_type",1);
                        JSONObject defaultValue=new JSONObject();
                        defaultValue.put("value",arr);
                        map.put("default_value",defaultValue.toJSONString());
                        list.add(map);
                    }
                }
            }
        }
        else{
            Map<String,Object> map=new HashMap<>();
            String uuid=UUID.randomUUID().toString();
            map.put("id",uuid);
            map.put("node",entityKey);
            map.put("node_key",uuid.replaceAll("-",""));
            if(entityUuid==null){
                map.put("parent_id","0");
            }
            else{
                map.put("parent_id",entityUuid);
            }
            map.put("data_type",5);
            map.put("valuation_type",0);
            list.add(map);
        }
    }

    public void dataType(Map<String,Object> map,String dataType,Object value){
        if("java.lang.String".equals(dataType)){
            if("false".equals(value) || "true".equals(value)){
                map.put("data_type",2);
            }
            else{
                map.put("data_type",1);
            }
        }
        else if("java.lang.Integer".equals(dataType)){
            map.put("data_type",3);
        }
        else if("java.math.BigDecimal".equals(dataType)){
            map.put("data_type",4);
        }
        else if("java.lang.Boolean".equals(dataType)){
            map.put("data_type",2);
        }

        map.put("valuation_type",1);

        JSONObject defaultValue=new JSONObject();
        if("java.math.BigDecimal".equals(dataType)){
            defaultValue.put("value", ((BigDecimal)value).doubleValue());

        }
        else{
            defaultValue.put("value",value);
        }

        map.put("default_value",defaultValue.toJSONString());

    }

    public List<Map<String,Object>> inPlmPartToList(List<Map<String,Object>> partList){
        List<Map<String,Object>> list=new ArrayList<>();
        inPlmPartToChildren(partList,list);
        return list;
    }
    public void inPlmPartToChildren(List<Map<String,Object>> list,List<Map<String,Object>> save){
        for(int i=0;i<list.size();i++){
            if(list.get(i).get("children")!=null){
                save.add(list.get(i));
                inPlmPartToChildren((List<Map<String, Object>>) list.get(i).get("children"),save);
            }
            else{
                save.add(list.get(i));
            }
        }
    }
    public void settingPlmPartToChildren(List<Map<String,Object>> list,List<Map<String,Object>> save,String parentId){
        for(int i=0;i<list.size();i++){
            if(parentId.equals(list.get(i).get("parent_id"))){
                Map<String,Object> node=new HashMap<>();
                node.put("label",list.get(i).get("node"));
                node.put("value",list.get(i).get("node_key"));
                if(node.containsKey("children")==false){
                    List<Map<String,Object>> children=new ArrayList<>();
                    node.put("children",children);
                }
                save.add(node);
                settingPlmPartToChildren(list, (List<Map<String, Object>>) node.get("children"), (String) list.get(i).get("id"));
            }
        }
    }
    public void settingPlmPartChildrenToNull(List<Map<String,Object>> list){
        for(int i=0;i<list.size();i++){
            if(list.get(i).containsKey("children")){
                List<Map<String,Object>> children= (List<Map<String, Object>>) list.get(i).get("children");
                if(children.size()==0){
                    list.get(i).remove("children");
                }
                else{
                    settingPlmPartChildrenToNull((List<Map<String, Object>>) list.get(i).get("children"));
                }
            }
        }
    }



}
